import { memo, forwardRef, useState, useImperativeHandle, ForwardRefRenderFunction, useEffect, SetStateAction } from 'react'
import { Modal, Form, Flex, Space, Row, Col, Button } from 'antd'
import { HsAdminForm, HsAdminInput, HsAdminTable, HsAdminTablePage } from '@hs-admin/base-components'
import { addDataCollect, editDataCollect, getDataCollectProductDataItemList, getDataCollectProductDetail } from '@/api/assetMaintain/dataProduct'
import { message, usePage } from '@hs-admin/utils'
import { reqDataItemList } from '@/api/assetMaintain/basic/item'
import { HsAdminSelectProductCategory, HsAdminSelectTheme } from '@/components/global'
import { useTableCheck } from '@/hooks/useTable'

interface Props {
  category_id: string | null
  finish: () => void
  source: 'item_set' | 'website'
}
const TableEdit: ForwardRefRenderFunction<unknown, Props> = (props: Props, ref: any) => {
  const { category_id, finish, source } = props
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [form] = Form.useForm()
  const [formValues, setformValues] = useState<any>({})
  const formItemOptions = [
    {
      label: '产品名称',
      name: 'name',
      required: true,
      component: 'Input'
    },
    {
      label: '产品描述',
      name: 'description',
      required: true,
      component: 'TextArea',
      componentProps: {
        autoSize: { minRows: 2, maxRows: 4 }
      }
    },
    {
      label: '产品类别',
      name: 'item_set_tag_id',
      required: true,
      slot: 'item_set_tag_id'
    }
  ]
  const columns1 = [
    {
      title: '产品名称',
      dataIndex: 'name'
    }
  ]
  const columns2 = [
    {
      title: '产品名称',
      dataIndex: 'name'
    },
    {
      title: '操作',
      dataIndex: 'actions',
      render: (_text: string, _record: any, index: number) => (
        <Button
          type="link"
          onClick={() => {
            setselectedData((prevState) => {
              prevState.splice(index, 1)
              setselectedRowKeys(prevState.map((item) => item.id))
            })
          }}>
          删除
        </Button>
      )
    }
  ]
  const { pagination, resetPage }: { pagination: UsePageProps; resetPage: () => void } = usePage(callDataItemList)
  const [data, setdata] = useState<any[]>([])

  const [topic_id, settopic_id] = useState<string | null>(null)
  const [keyword, setkeyword] = useState<string | null>(null)
  const [categoryOptions, setcategoryOptions] = useState<any[]>([])
  const { selectedRowKeys, setselectedRowKeys, selectedData, setselectedData, rowSelection } = useTableCheck()

  const handleOk = async () => {
    form
      .validateFields()
      .then(async (values) => {
        const params: any = {
          ...formValues,
          ...values,
          category_id,
          item_ids: selectedRowKeys
        }
        let callFn = addDataCollect
        let text = '新增成功'
        if (params.id) {
          callFn = editDataCollect
          text = '编辑成功'
        }
        await callFn(params)
        message.success(text)
        finish()
        handleCancel()
      })
      .catch((error) => {
        return Promise.reject(error)
      })
  }
  const handleCancel = () => {
    resetPage()
    form.resetFields()
    setformValues({})
    setdata([])
    setselectedData([])
    setselectedRowKeys([])
    settopic_id(null)
    setkeyword(null)
    setIsModalOpen(false)
  }
  const showModal = (item: any) => {
    if (item) {
      getDataCollectProductDetail({
        id: item.id
      }).then((res) => {
        setformValues(res)
        form.setFieldsValue({ ...res, item_set_tag_id: res.item_set_tag?.id })
        setcategoryOptions([{ label: res.item_set_tag?.name, value: res.item_set_tag?.id }])
        getDataCollectProductDataItemList({ id: item.id, page_size: 99 }).then((res) => {
          setselectedData(res.items ?? [])
          setselectedRowKeys(res.items?.map((item: any) => item.id) ?? [])
        })
      })
    }
    setIsModalOpen(true)
  }
  function callDataItemList() {
    return reqDataItemList({
      data_topic_id: topic_id,
      keywords: keyword,
      page: pagination.current,
      page_size: pagination.pageSize
    }).then((res) => {
      setdata(res.items)
      return res
    })
  }
  function callSearchDataItem(key: 'topic_id' | 'keyword', value: string) {
    switch (key) {
      case 'topic_id':
        settopic_id(value)
        break
      case 'keyword':
        setkeyword(value)
        break
      default:
        break
    }
    resetPage()
  }

  useEffect(() => {
    callDataItemList()
  }, [topic_id, keyword])

  useImperativeHandle(
    ref,
    () => {
      return {
        showModal
      }
    },
    []
  )

  return (
    <Modal title="新增/编辑数据服务" open={isModalOpen} onOk={handleOk} onCancel={handleCancel} width={1000} centered>
      <HsAdminForm form={form} formItemOptions={formItemOptions} labelCol={{ span: 2 }} wrapperCol={{ span: 22 }}>
        <div slot="item_set_tag_id">
          <Form.Item name="item_set_tag_id">
            <HsAdminSelectProductCategory options={categoryOptions} source={source} />
          </Form.Item>
        </div>
      </HsAdminForm>
      <h2 className="font-bold">基础数据</h2>
      <Flex gap="middle">
        <Flex align="center">
          <span>所属主题：</span>
          <HsAdminSelectTheme value={topic_id} onChange={(value: string) => callSearchDataItem('topic_id', value)} style={{ width: 240 }} />
        </Flex>
        <Space align="center">
          <span>数据项名称：</span>
          <HsAdminInput
            value={keyword}
            onChange={(e: { target: { value: SetStateAction<string | null> } }) => setkeyword(e.target.value)}
            onPressEnter={(e: { target: { value: string } }) => callSearchDataItem('keyword', e.target.value)}
            onBlur={(e: { target: { value: string } }) => callSearchDataItem('keyword', e.target.value)}
          />
        </Space>
      </Flex>
      <br />
      <Row gutter={[16, 0]}>
        <Col span={12}>
          <p>全部</p>
          <HsAdminTablePage
            columns={columns1}
            dataSource={data}
            pagination={pagination}
            rowKey="id"
            size="small"
            rowSelection={{ selectedRowKeys, ...rowSelection }}
            id="J-item-set-child-update"
          />
        </Col>
        <Col span={12}>
          <p>已选择 {selectedData.length} 个</p>
          <div className="overflow-y-auto h-103">
            <HsAdminTable columns={columns2} dataSource={selectedData} pagination={false} rowKey="id" size="small" id="J-item-set-child-edit-modal" />
          </div>
        </Col>
      </Row>
    </Modal>
  )
}

export default memo(forwardRef(TableEdit))
